#!/bin/bash
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2019 Joyent, Inc.
#

#
# MDB is pernickety about the exact format of this output, so be
# careful. In particular the json-4 formatting/spacing is required.
#

set -o errexit
set -o pipefail

export PATH=/opt/local/bin/:$PATH

ber_arg0=$(basename $0)
ber_wsroot=$(cd "$(dirname "$0")/.." && pwd)
ber_first=true

ber_template="                     SmartOS %%VERSION%% x86_64
                       Copyright %%YEAR%% Joyent, Inc.

  Built with the following components:
"

function fatal
{
	local msg="$*"
	[[ -z "$msg" ]] && msg="failed"
	printf '%s: %s\n' "$ber_arg0" "$msg" >&2
	exit 1
}

function warn
{
	local msg="$*"
	[[ -z "$msg" ]] && msg="failed"
	printf '%s: %s\n' "$ber_arg0" "$msg" >&2
}

function get_status
{
	local dir=$1 name=$2 cont=$3
	local branch rev comdate name url prevdir

	[[ -z "$dir" ]] && fatal "missing directory argument"
	[[ -z "$name" ]] && fatal "missing name"
	[[ -d $dir ]] || fatal "asked to get status of non-existant directory"

	prevdir=$PWD
	if ! cd "$dir"; then
		fatal "failed to chdir to \"$dir\""
	fi

	if [[ $ber_first != true ]]; then
		printf ',\n'
	else
		ber_first=false
	fi
	printf '  '

	if [[ ! -d .git ]]; then
		#
		# This means that we have a local project that isn't a git
		# directory.  Yay team. In this case we just give them a date
		# and move on with life.
		#
		if ! comdate=$(date +%s); then
			fatal "failed to get current date"
		fi
		warn "no git repository information available"

		printf '  { "repo": "%s", "date": "%s",\n' \
		    "$name" "$comdate"
		printf '      "warning": "no git metadata available" }'
	else
		if ! url=$(git config remote.origin.url); then
			fatal "failed to get git origin url"
		fi
		if ! branch=$(git branch | grep "^* " | cut -d ' ' -f2-); then
			fatal "failed to get git branch"
		fi
		if ! rev=$(git rev-parse HEAD); then
			fatal "failed to get current revision"
		fi
		if ! comdate=$(git log -n 1 --pretty=format:%ct HEAD); then
			fatal "failed to get commit date"
		fi

		printf '  { "repo": "%s", "branch": "%s",\n' \
		    "$name" "$branch"
		printf '      "commit_date": "%s",\n' \
		    "$comdate"
		printf '      "rev": "%s",\n' \
		    "$rev"
		printf '      "url": "%s" }' \
		    "$url"
	fi

	if ! cd "$prevdir"; then
		fatal "failed to chdir back to \"$prevdir\""
	fi

	return 0
}

function usage {
	echo "Usage: build_etcrelease <options>"
	echo "    -g                  emit gitstatus.json content"
	echo "    -h                  print this message"
	echo "    -v <version>        emit an etc/release file with <version>,"
	echo "                        including the gistatus.json content."
	echo ""
}

while getopts "ghv:" opt; do
	case "${opt}" in
		g)
			do_gitstatus=true
			;;
		h)
			do_help=true
			;;
		v)
			ber_version=$OPTARG
			;;
		*)
			warn "unknown option ${opt}"
			usage
	esac
done
shift $((OPTIND - 1))

if [[ -z "$do_help" && -z "$do_gitstatus" && -z "$ber_version" ]]; then
	usage
	exit 2
fi

if [[ -n "$do_help" ]]; then
	usage
	exit 2
fi

if [[ -n "$ber_version" ]]; then
	ber_year=$(date +%Y)
	ber_content=$(echo "$ber_template" | \
	    sed -e "s,%%VERSION%%,$ber_version,g" \
		-e "s,%%YEAR%%,$ber_year,g");
	printf '%s\n\n' "$ber_content"
fi

( printf '[\n'
get_status "$ber_wsroot" smartos-live
get_status "$ber_wsroot/projects/illumos" illumos-joyent
get_status "$ber_wsroot/projects/illumos-extra" illumos-extra
for d in $ber_wsroot/projects/local/*; do
	get_status $d $(basename $d)
done

printf '\n]\n' ) | json -o json-4

exit 0
